//
//  PPHospitalTableViewController.m
//  pet
//
//  Created by 陈无忌 on 12/18/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPHospitalTableViewController.h"
#import "ChatViewController.h"
#import "PPDoctorCollectionViewCell.h"
#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"

@interface PPHospitalTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (strong, nonatomic) NSArray *imageArray;
@property (strong, nonatomic) NSMutableArray *doctorArray;

@property (weak, nonatomic) IBOutlet UIScrollView *imagePlayerView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UICollectionView *doctorCollectionView;
@property (weak, nonatomic) IBOutlet UILabel *introductionLabel;

@property (weak, nonatomic) PPSystemConfiguraton *config;



@end


@implementation PPHospitalTableViewController
- (NSMutableArray *)doctorArray
{
    if (!_doctorArray) {
        _doctorArray = [NSMutableArray array];
    }
    return _doctorArray;
}

- (PPSystemConfiguraton *)config{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *imageOne = [UIImage imageNamed:@"mainPicture"];
    UIImage *imageTwo = [UIImage imageNamed:@"secondPicture"];
    UIImage *imageThree = [UIImage imageNamed:@"thirdPicture"];
    self.imageArray = [[NSArray alloc] initWithObjects:imageOne,imageTwo,imageThree, nil];

    self.doctorCollectionView.delegate = self;
    self.doctorCollectionView.dataSource = self;
    
    [self getDoctor];
    
    [self setImagePlayerView];
    
    self.introductionLabel.numberOfLines = 6;
    self.introductionLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [self.introductionLabel sizeToFit];
}

- (void)getDoctor
{
    NSString *url = [PPAPIList getAPIList].PPQueryFriendByPhoneNum;
    NSDictionary *params = @{@"phoneNum":@"15005812873"};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *err = nil;
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            [self.doctorArray removeAllObjects];
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSDictionary *friend = resultMap[@"friend"];
            PPUserInfo *doctor = [[PPUserInfo alloc]initWithDictionary:friend error:&err];
            [self.doctorArray addObject:doctor];
            [self.doctorCollectionView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

- (void)setImagePlayerView
{
    self.imagePlayerView.bounces = YES;
    self.imagePlayerView.pagingEnabled = YES;
    self.imagePlayerView.delegate = self;
    self.imagePlayerView.userInteractionEnabled = YES;
    self.imagePlayerView.showsHorizontalScrollIndicator = NO;
    
    [self.pageControl setCurrentPageIndicatorTintColor:[UIColor blackColor]];
    [self.pageControl setPageIndicatorTintColor:[UIColor grayColor]];
    self.pageControl.numberOfPages = [self.imageArray count];
    self.pageControl.currentPage = 0;
    
    for (int i = 0;i<[self.imageArray count];i++)
    {
        UIImage *image = [self.imageArray objectAtIndex:i];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((320 * i), 0, 320, 153)];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        [imageView setClipsToBounds:YES];
        [imageView setImage:image];
        [self.imagePlayerView addSubview:imageView];
    }
    [self.imagePlayerView setContentSize:CGSizeMake(320 * self.imageArray.count, 153)];
    [self.imagePlayerView setContentMode:UIViewContentModeScaleAspectFill];
    [self.imagePlayerView scrollRectToVisible:CGRectMake(320*self.pageControl.currentPage,0,320,153) animated:NO];
}

// scrollview 委托函数
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    CGFloat pagewidth = self.imagePlayerView.frame.size.width;
    int page = floor((self.imagePlayerView.contentOffset.x - pagewidth/2)/pagewidth) + 1;
    self.pageControl.currentPage = page;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - Collection view data source
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.doctorArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPUserInfo *doctor = [self.doctorArray objectAtIndex:indexPath.row];
    PPDoctorCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"doctorCell" forIndexPath:indexPath];
    [cell.avatar setImageWithURL:[PPImageUrl getImageUrl:doctor.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    cell.doctorNameLabel.text = doctor.userName;
    return cell;
}


#pragma mark - Collection view delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PPUserInfo *doctor = [self.doctorArray objectAtIndex:indexPath.row];

    [self goChat:doctor];
}

- (BOOL)checkFriend:(PPUserInfo *)doctor
{
    NSArray *buddys = [[EaseMob sharedInstance].chatManager buddyList];
    NSMutableArray *usernames = [NSMutableArray array];
    //循环取得 EMBuddy 对象
    for (EMBuddy *buddy in buddys) {
        //屏蔽发送了好友申请, 但未通过对方接受的用户
        if (!buddy.isPendingApproval) {
            [usernames addObject:buddy.username];
        }
    }
    for (NSString *userName in usernames) {
        if (userName.intValue == doctor.id) {
            return YES;
        }
    }
    return NO;
}

- (void)getConversation:(PPUserInfo *)doctor
{
    NSString *url = [PPAPIList getAPIList].PPQueryConversationByTargetId;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(doctor.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //查询成功 直接得到会话传入
            NSError *err = nil;
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSDictionary *conversationDic = resultMap[@"conversation"];
            PPConversation *conversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
            conversation.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:conversation.targetId isGroup:[NSNumber numberWithInt:conversation.isGroup].boolValue];
            
            [conversation.conversation markMessagesAsRead:YES];
            ChatViewController *targetVC = [[ChatViewController alloc] initWithChatter:conversation.targetId];
            
            targetVC.myConversation = conversation;
            targetVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:targetVC animated:YES];
        }else{
            //查询失败 这创建新的会话
            NSString *url = [PPAPIList getAPIList].PPCreateConversation;
            NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"targetId":@(doctor.id),@"isGroup":@(0)};
            [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber *processResult = responseObject[@"processResult"];
                if (processResult.boolValue) {
                    NSError *err = nil;
                    NSDictionary *resultMap = responseObject[@"resultMap"];
                    NSDictionary *conversationDic = resultMap[@"conversation"];
                    PPConversation *conversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
                    conversation.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:conversation.targetId isGroup:[NSNumber numberWithInt:conversation.isGroup].boolValue];
                    [conversation.conversation markMessagesAsRead:YES];
                    ChatViewController *targetVC = [[ChatViewController alloc] initWithChatter:conversation.targetId];
                    targetVC.myConversation = conversation;
                    targetVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:targetVC animated:YES];
                }else{
                    [PPHUD hudShowWithString:@"会话创建失败" andView:self.view];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
            }];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
    }];
}

- (void)goChat:(PPUserInfo *)doctor
{
    if ([self checkFriend:doctor]) {
        [self getConversation:doctor];
    }else{
        EMError *error;
        [[EaseMob sharedInstance].chatManager addBuddy:[NSString stringWithFormat:@"%d",doctor.id] message:@"医生你好我想给宠物看病" error:&error];
        if (!error) {
            [self getConversation:doctor];
        }else{
            [PPHUD hudShowWithString:@"无法与医生取得联系" andView:self.view];
        }
    }
    [self.config getConversationListwithComepletion:nil];
}
/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
